/*
 *      timer.c
 *
 *      Copyright 2007 Giulio Bai <giulio@hewle.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include <sys.h>
#include <dev.h>
#include <irq.h>
#include <timer.h>

/* keep track of how many ticks the system has been running for */


/* Sets timer frequency */
void timer_phase (int hz)
{
	int divisor = 1193180 / hz;          /* Calculate divisor */

	outportb (0x43, 0x36);            /* Set command byte 0x36 */
	outportb (0x40, divisor & 0xFF);  /* Set low byte of divisor */
	outportb (0x40, divisor >> 8);    /* Set high byte of divisor */
}


/* Handles the timer. Increment timer_ticks every time the timer fires.
 * The timer fires 18.222 times per second.
 * don't ask me why, but it's evident some engeneer at IBM must've got
 * drunk that night */
void timer_handler (struct regs *r)
{
	/* Increment our tick count */
	sinfo.uptime ++;

	/* 18 clocks are almost 1 second */
	/* if (timer_ticks % 18 == 0) one_sec_passed (); */
}


/* Continuously loop until the given time has been reached.
 * This function is similar to the delay () one from standard c */
void timer_delay (int ticks)
{
	unsigned long eticks;

	eticks = sinfo.uptime + ticks;

	while (sinfo.uptime < eticks);
}


/* Sets up the system clock by installing the timer handler in IRQ0.
 * it also sets the starting timer frequency */
void timer_install (int hz)
{
	sinfo.uptime = 0;
	
	/* Sets timer_phase */
	timer_phase (hz);
	
	/* Installs timer_handler to IRQ0 */
	irq_install_handler (0, timer_handler);
	
	printi ("timer", 1, 1);
}
